package com.zhishu.portal.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhishu.model.DataConfig;
import com.zhishu.model.Result;
import com.zhishu.model.TableList;
import com.zhishu.model.TaskPage;
import com.zhishu.model.TaskPageParse;
import com.zhishu.model.Template;
import com.zhishu.portal.common.result.Page;
import com.zhishu.portal.queue.HttpMQProducer;
import com.zhishu.portal.util.Const;

@Component
public class MyService {

	private static Logger logger = Logger.getLogger(MyService.class);

	@Resource
	private NutDao mysqlDao;

	public Page getPageData(Long user_id, String request_id, Integer index) {

		Page ret = new Page();
		try {
			TaskPage job = mysqlDao.fetch(TaskPage.class,
					Cnd.where("request_id", "=", request_id).and("page", "=", index));
			if (job == null) {
				return ret;
			}
			String requestid = job.getRequest_id();
			int count = mysqlDao.count(TaskPage.class, Cnd.where("request_id", "=", requestid));
			TaskPageParse page = mysqlDao.fetch(TaskPageParse.class,
					Cnd.where("tpid", "=", job.getId()).and("user_id", "=", user_id));
			if (page != null) {
				JSONArray array = JSONObject.parseArray(page.getResult());
				ret = new Page(count, job.getPage(), array.size());
				ret.setMaxPage(count);
				ret.setPage(job.getPage());

				String[] ts = page.getHead().split(",");
				ret.setInfo(ts);

				ret.setData(array);
				ret.setCode(Const.SUC);
			} else {
				ret.setData(new JSONArray());
				ret.setCode(Const.SUC);
			}

			return ret;
		} catch (Exception e) {
			logger.info("", e);
			ret.setCode(Const.FAIL);

		}
		return ret;
	}

	public List<Template> getMyTemplateList(Long user_id) {
		List<Template> list = new ArrayList<Template>();
		try {
			list = mysqlDao.query(Template.class, Cnd.where("user_id", "=", user_id));
			for (Template tmpl : list) {

				List<TaskPage> pageList = mysqlDao.query(TaskPage.class, Cnd.where("tid", "=", tmpl.getId()));

				tmpl.setPageList(pageList);
			}
		} catch (Exception e) {
			logger.info("", e);

		}
		return list;
	}

	public List<Template> getMyConfigList(Long user_id) {

		try {
			List<Template> tlist = mysqlDao.query(Template.class, Cnd.where("user_id", "=", user_id));

			return tlist;
		} catch (Exception e) {
			logger.info("", e);

		}
		return null;
	}

	public Template getTemplate(String request_id) {

		try {
			Template tlist = mysqlDao.fetch(Template.class, Cnd.where("request_id", "=", request_id));

			return tlist;
		} catch (Exception e) {
			logger.info("", e);

		}
		return null;
	}

	public Boolean saveTemplateConfig(String id, String template_name, String pageRule, String taskRule,
			Integer minPage, Integer maxPage, String byType, Date start_date, Date end_date) {
		Boolean flag = false;
		try {
			Date date = new Date();

			long tid = Long.parseLong(id);
			Template config = mysqlDao.fetch(Template.class, Cnd.where("id", "=", tid));

			if (config == null) {
				return false;
			} else {

				config.setPage_rule(pageRule);
				config.setTask_rule(taskRule);
				config.setTemplate_name(template_name);
				config.setStart_date(start_date);
				config.setEnd_date(end_date);
				config.setMin_page(minPage);
				config.setMax_page(maxPage);
				config.setJobStatus(-1);
				config.setUpdate_time(date);
				config.setByType(byType);
				mysqlDao.updateIgnoreNull(config);

				mysqlDao.clear(TaskPage.class, Cnd.where("tid", "=", tid));

				String prule = config.getPage_rule();

				int index = prule.indexOf("[[");
				int last = prule.indexOf("]]");

				if (index > 0 && last > 0) {
					String furl = prule.substring(0, index);

					String lurl = prule.substring(last + 2, prule.length());
					for (int i = minPage; i <= maxPage; i++) {
						String pageUlr = furl + i + lurl;
						TaskPage tp = new TaskPage();
						tp.setRequest_id(config.getRequest_id());
						tp.setTid(tid);
						tp.setUser_id(config.getUser_id());
						tp.setStatus(0);
						tp.setPage(i);
						tp.setPage_url(pageUlr);
						tp.setCreate_time(new Date());
						tp.setJob_id(config.getRequest_id() + "-" + i);
						mysqlDao.fastInsert(tp);
					}
				} else {

					TaskPage tp = new TaskPage();
					tp.setRequest_id(config.getRequest_id());
					tp.setTid(tid);
					tp.setUser_id(config.getUser_id());
					tp.setStatus(0);
					tp.setPage(1);
					tp.setPage_url(prule);
					tp.setCreate_time(new Date());
					tp.setJob_id(config.getRequest_id() + "-" + 1);
					mysqlDao.fastInsert(tp);

				}

			}
			flag = true;
		} catch (Exception e) {
			logger.info("", e);
		}
		return flag;
	}

	public Result doStartJob(String tid) {
		Result ret = new Result();
		try {

			Template config = mysqlDao.fetch(Template.class, Cnd.where("id", "=", tid));

			String msg = JSON.toJSONString(config);
			JSONObject send = HttpMQProducer.send(Const.topic, Const.pid, msg, "job");
			if (send.getString("sendStatus").equals("SEND_OK")) {
				mysqlDao.update(Template.class, Chain.make("job_status", 0), Cnd.where("id", "=", tid));
			} else {
				mysqlDao.update(Template.class, Chain.make("job_status", 3), Cnd.where("id", "=", tid));
			}

			ret.setResult(Const.SUC, "处理成功");
		} catch (Exception e) {
			logger.info("", e);
			ret.setResult(Const.FAIL, "处理异常");
		}
		return ret;
	}

	public static void main(String[] args) {
		String url = "http://www.yanjiao.com/forum-327-[[page]].html";
		int index = url.indexOf("[[");
		int last = url.indexOf("]]");
		String furl = url.substring(0, index);

		String lurl = url.substring(last + 2, url.length());

		System.out.println(furl);
		System.out.println(lurl);

	}

	 public List<DataConfig> getDataConfig(Long id) {
	        List<DataConfig> list = mysqlDao.query(DataConfig.class, Cnd.where("user_id", "=", id));
	        for (int i = 0; i < list.size(); i++) {
	            List<TableList> tableLists = mysqlDao.query(TableList.class, Cnd.where("table_id", "=", list.get(i).getId()));
	            list.get(i).setTableList(tableLists);
	        }
	        return list;
	    }

	public Boolean addSaveDataSourse(String type, String host, String port, String username, String password,
			String sqldb, Long user_id) {
		Boolean flag = false;
		try {
			DataConfig dataConfig = new DataConfig();
			dataConfig.setDb(sqldb);
			dataConfig.setHost(host);
			dataConfig.setPort(port);
			dataConfig.setPwd(password);
			dataConfig.setType(type);

			dataConfig.setUsername(username);
			dataConfig.setUser_id(user_id);
			dataConfig.setCreate_time(new Date());
			String url = "";
			if (type.equalsIgnoreCase("oracle")) {
				url = "jdbc:oracle:thin:@" + dataConfig.getHost() + ":" + dataConfig.getPort() + ":"
						+ dataConfig.getDb();
			} else if (type.equalsIgnoreCase("sqlserver")) {
				url = "jdbc:sqlserver://" + dataConfig.getHost() + ":" + dataConfig.getPort() + ";DatabaseName="
						+ dataConfig.getDb();
			} else if (type.equalsIgnoreCase("db2")) {
				url = "jdbc:db2://" + dataConfig.getHost() + ":" + dataConfig.getPort() + "/" + dataConfig.getDb();
			} else if (type.equalsIgnoreCase("mysql")) {
				url = "jdbc:mysql://" + dataConfig.getHost() + ":" + dataConfig.getPort() + "/" + dataConfig.getDb()
						+ "?useUnicode=true&characterEncoding=UTF-8";
			} else {
				url = type;
			}
			dataConfig.setUrl(url);
			mysqlDao.insert(dataConfig);
			flag = true;
		} catch (Exception e) {
			logger.info("", e);
		}
		return flag;
	}

	public Boolean modifySaveDataSourse(String sqltype, String host, String port, String sqlurl, String username,
			String password, String sqldb, String id) {
		Boolean flag = false;
		try {
			Long Id = Long.parseLong(id);
			mysqlDao.update(DataConfig.class,
					Chain.make("db", sqldb).add("host", host).add("port", port).add("pwd", password)
							.add("sql_type", sqltype).add("sql_url", sqlurl).add("username", "username"),
					Cnd.where("id", "=", Id));
			flag = true;
		} catch (Exception e) {
			logger.info("", e);
		}
		return flag;
	}

	public Boolean delDataSource(Long id) {
		Boolean flag = false;
		try {
			mysqlDao.delete(DataConfig.class, id);
			flag = true;
		} catch (Exception e) {
			logger.info("", e);
		}
		return flag;
	}

	public boolean testConnection(Long id) {
		Boolean flag = false;
		DataConfig dataConfig = mysqlDao.fetch(DataConfig.class, Cnd.where("id", "=", id));
		Connection con = null;
		try {
			if (dataConfig.getType().equals("mysql")) {
				Class.forName("com.mysql.jdbc.Driver");
				con = DriverManager.getConnection(dataConfig.getUrl(), dataConfig.getUsername(), dataConfig.getPwd());
			} else if (dataConfig.getType().equals("sqlserver")) {
				Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
				con = DriverManager.getConnection(dataConfig.getUrl(), dataConfig.getUsername(), dataConfig.getPwd());
			} else if (dataConfig.getType().equals("oracle")) {
				Class.forName("oracle.jdbc.driver.OracleDriver");
				con = DriverManager.getConnection(dataConfig.getUrl(), dataConfig.getUsername(), dataConfig.getPwd());
			} else if (dataConfig.getType().equals("postgresql")) {
				Class.forName("org.postgresql.Driver");
				con = DriverManager.getConnection(dataConfig.getUrl(), dataConfig.getUsername(), dataConfig.getPwd());
			}
			System.out.println("连接成功");
			flag = true;
		} catch (Exception e) {
			logger.info("", e);
		}
		return flag;
	}
}
